select  count(p.state) num
from realty_object ro
    join price p on p.realty_object_id = ro.id
      where  p.date = (select max(sp.date) from price sp where sp.realty_object_id = ro.id)
      and p.state in (0,1) and ro.${realtyType}_details_id is not null
order by p.state desc, ro.id asc
